package org.zfes.snowier.zbss.xzy.store.meta;

import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.zfes.snowier.common.redis.RedisHelper;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

public class RedisMetaCache implements TableMetaCache {
	
	private static final String key_prefix="mo_tb_";
	
	@Autowired
	private RedisTemplate<String,String> redisTemplate;
	
	
	@Override
	public Map<String,Set<String>> getAllTables(){
		Map<String,Set<String>> data = Maps.newHashMap();
		Cursor<String> cursor=RedisHelper.scan(redisTemplate,  "*"+key_prefix+"*", 200);
		while(cursor.hasNext()) {
			String key=new String(cursor.next().getBytes());
			
			Set<String> members = redisTemplate.opsForSet().members(key);
			
			data.put(key.replace(key_prefix, ""), members);
		}
		return data;
	}
	@Override
	public  Set<String> getCols(String tablename) {
		if(!isTableExists( tablename)) {
			return Sets.newHashSet();
		}
		return redisTemplate.opsForSet().members(key_prefix+tablename);
		
	}
	@Override
	public  boolean isTableExists(String tablename) {
		return redisTemplate.hasKey(key_prefix+tablename);
	}
	
	@Override
	public  boolean isColExists(String tablename,String colname) {
		if(isTableExists( tablename)) {
			return redisTemplate.opsForSet().isMember(key_prefix+tablename, colname);
		}
		return false;
	}
	
	
	@Override
	public  void addTable(String tablename,Set<String> cols) {
		redisTemplate.opsForSet().add(key_prefix+tablename, cols.stream().toArray(String[]::new));
		
	}
	
	@Override
	public  void addTables(Map<String,Set<String>> tableMetaMap) {
		
		if(tableMetaMap==null||tableMetaMap.isEmpty()) {
			return ;
		}
		
		tableMetaMap.forEach((key, value)->addTable(key,value));
	}
	
	@Override
	public  void removeTable(String tablename) {
		redisTemplate.delete(key_prefix+tablename);
	}
	
	@Override
	public  void addCols(String tablename,Set<String> cols) {
		addTable( tablename, cols);
	}
	
	@Override
	public  void addCol(String tablename,String col) {
		addTable( tablename, Sets.newHashSet(col));
	}
	@Override
	public  void removeCol(String tablename,String col) {
		if(!isTableExists( tablename)) {
			return;
		}
		 redisTemplate.opsForSet().remove(key_prefix+tablename,col);
	}
	
}
